import cv2
import numpy as np
import random
import time

def show(image,name="image"):

    h = image.shape[0]
    w = image.shape[1]

    # cv2.namedWindow('window', cv2.WINDOW_AUTOSIZE)
    cv2.imshow("%s,%d,%d"%(name,h,w), image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def calcuImageArticulate(img):
    """
    计算图片清晰度
    模糊的照片怎么去衡量呢？根据参考大量的方案-对图像进行梯度求解然后求方差，以方差的值作为评价图像的清晰程度。
    最为常用的或者说最为经典的是拉普拉斯算子进行的梯度计算
    图像-》灰度-》拉普拉斯-》方差。
    :param img:
    :return: int
    """
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    articulate = cv2.Laplacian(img_gray, cv2.CV_64F).var()
    # articulate = float("%.4f"%(articulate))
    articulate = int(articulate)
    return articulate

def calcuImageDark(img):
    """
    计算图片暗色像素的占比
    :param img:
    :return:
    """

    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    h, w = gray_img.shape[:2]

    pix_sum = h * w

    # 计算方法一
    gray_img_1x = gray_img.reshape(pix_sum)
    gray_img_1x_dark = gray_img_1x[np.where(gray_img_1x < 50)]
    dark_pix_sum = gray_img_1x_dark.size

    # 计算方法二 (耗时是方法一的几百倍)
    # dark_pix_sum = 0
    # for row in range(h):
    #     for col in range(w):
    #         pix = gray_img[row,col]
    #         if pix <= 50:# 人为设置的超参数
    #             dark_pix_sum +=1


    dark_prop = dark_pix_sum / pix_sum
    dark_prop = float("%.2f"%(dark_prop))
    return dark_prop

def calcuTwoImageSimilary(img1, img2):
    """
    计算两张图片的相似度
    :param img1:
    :param img2:
    :return:
    """
    def calculate(image1, image2):
        # 灰度直方图算法
        # 计算单通道的直方图的相似值
        hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
        hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
        # 计算直方图的重合度
        degree = 0
        for i in range(len(hist1)):
            if hist1[i] != hist2[i]:
                degree = degree + \
                         (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
            else:
                degree = degree + 1
        degree = degree / len(hist1)
        return degree


    def classify_hist_with_split(image1, image2, size=(256, 256)):
        # RGB每个通道的直方图相似度
        # 将图像resize后，分离为RGB三个通道，再计算每个通道的相似值
        image1 = cv2.resize(image1, size)
        image2 = cv2.resize(image2, size)
        sub_image1 = cv2.split(image1)
        sub_image2 = cv2.split(image2)
        sub_data = 0
        for im1, im2 in zip(sub_image1, sub_image2):
            sub_data += calculate(im1, im2)

        sub_data = sub_data / 3
        return sub_data


    similary = classify_hist_with_split(img1, img2)
    similary = float(similary[0]) # 0.3441087305545807,,

    # print('三直方图算法相似度1：', type(similary),similary)

    return similary


def cutImage(image, cut_h, cut_w):
    h, w, c = image.shape

    h_resize = cut_h
    w_resize = int(h_resize * (w / h))

    if w_resize < cut_w:
        # 如果按照高的标准缩小后，宽度小于目标宽度。则宽度置为目标宽度，高度相应比例缩小
        w_resize = cut_w
        h_resize = int(w_resize * (h / w))

    image = cv2.resize(image, (w_resize, h_resize), interpolation=cv2.INTER_NEAREST)

    y0 = 0
    y1 = cut_h
    x0 = int((w_resize - cut_w) / 2)
    x1 = x0 + cut_w

    return image[y0:y1, x0:x1]  # 裁剪坐标为[y0:y1, x0:x1]

def putImageInBg(image, bg_h, bg_w):

    bg = np.zeros((bg_h,bg_w,3),dtype=np.uint8)

    bg[:,:,0] = 255
    bg[:,:,1] = 255
    bg[:,:,2] = 255

    h,w,_ = image.shape

    change_h = bg_h - h
    change_w = bg_w - w

    if change_h>=0 and change_w >=0:
        y0 = random.randint(0,change_h)
        x0 = random.randint(0,change_w)

        bg[y0:y0+h,x0:x0+w] = image

    return bg

if __name__ == '__main__':

    img = cv2.imread("D:\\file\\t1\\0.jpg")
    h, w, c = img.shape
    print(h,w,c)
    # show(img)
    t1 = time.time()
    dark = calcuImageDark(img)
    t = time.time() - t1
    print("dark=%.4f,spend=%.4f"%(dark,t))

    t1 = time.time()
    art = calcuImageArticulate(img)
    t = time.time() - t1
    print("art=%.4f,spend=%.4f" % (art, t))

    # img2 = cv2.resize(img, (int(w/2),int(h/2)), interpolation=cv2.INTER_NEAREST)
    # h, w, c = img2.shape
    # print(h,w,c)
    # show(img2)
